package www.openteam.com.ui.realtime;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.cundong.recyclerview.EndlessRecyclerOnScrollListener;
import com.cundong.recyclerview.HeaderAndFooterRecyclerViewAdapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import www.openteam.com.R;
import www.openteam.com.adapter.ProAdapter;
import www.openteam.com.base.mBaseFragment;
import www.openteam.com.bean.ProducePro;
import www.openteam.com.contract.realtime.ProduceScheduleContract;
import www.openteam.com.presenter.realtime.ProduceSchedulePresenter;
import www.openteam.com.tool.RecyclerViewStateUtils;
import www.openteam.com.tool.ToastUtil;
import www.openteam.com.ui.DetailedActivity;
import www.openteam.com.widget.LoadingFooter;

/**
 * Created by kylin on 2017/1/5.\
 * 生产进度 5
 */

public class ProduceScheduleFragment extends mBaseFragment<ProduceSchedulePresenter> implements
        ProduceScheduleContract.ProduceScheduleView {

    @Bind(R.id.ed_1)
    EditText ed_1;
    @Bind(R.id.ed_2)
    EditText ed_2;
    @Bind(R.id.ed_3)
    EditText ed_3;
    @Bind(R.id.ed_4)
    EditText ed_4;
    @Bind(R.id.ed_5)
    EditText ed_5;
    @Bind(R.id.query_btn)
    Button query_btn;
    @Bind(R.id.tv_1)
    TextView tv_1;
    @Bind(R.id.tv_2)
    TextView tv_2;
    @Bind(R.id.tv_3)
    TextView tv_3;
    @Bind(R.id.tv_4)
    TextView tv_4;
    @Bind(R.id.tv_5)
    TextView tv_5;
    @Bind(R.id.btn1)
    Button btn1;
    @Bind(R.id.btn2)
    Button btn2;
    @Bind(R.id.btn3)
    Button btn3;

    View view;
    private ArrayList<ProducePro.DataEntity> produceSchedules;          //送货进度实体类
    private static int pageSize = 0;
    private final String TAG = ProduceScheduleFragment.class.getSimpleName();
    int i = 0;
    private HeaderAndFooterRecyclerViewAdapter mFooterRecyclerViewAapter = null;
    private ProAdapter produceScheduleAdapter = null;
    Throwable throwable = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        detailGather = ((DetailedActivity) getActivity()).getDetailGather();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        measurementLayoutHeight();
    }

    @Override
    protected void initView() {

        final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        int current_day = c.get(Calendar.DAY_OF_MONTH);
        int current_month = c.get(Calendar.MONTH);
        int current_year = c.get(Calendar.YEAR);
        c.set(current_year, current_month, current_day);
        ed_3.setText(df.format(c.getTime()));
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//一周内
                Calendar c = Calendar.getInstance();
                int current_day = c.get(Calendar.DAY_OF_MONTH);
                int current_month = c.get(Calendar.MONTH);
                int current_year = c.get(Calendar.YEAR);
                c.set(current_year, current_month, current_day);
                c.add(Calendar.DATE, -7);
                ed_4.setText(df.format(c.getTime()));
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//一月内
                Calendar c = Calendar.getInstance();
                int current_day = c.get(Calendar.DAY_OF_MONTH);
                int current_month = c.get(Calendar.MONTH) - 1;
                int current_year = c.get(Calendar.YEAR);
                c.set(current_year, current_month, current_day);
//                ed_3.setText(df.format(c.getTime()));
//                c.add(Calendar.DATE, 0);
                ed_4.setText(df.format(c.getTime()));
            }
        });

        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//一年内
                Calendar c = Calendar.getInstance();
                int current_day = c.get(Calendar.DAY_OF_MONTH);
                int current_month = c.get(Calendar.MONTH);
                int current_year = c.get(Calendar.YEAR) - 1;
                c.set(current_year, current_month, current_day);
//                ed_3.setText(df.format(c.getTime()));
//                c.add(Calendar.DATE, 0);
                ed_4.setText(df.format(c.getTime()));
            }
        });

        query_btn.setOnClickListener(new View.OnClickListener() {  //查询按钮
            @Override
            public void onClick(View v) {
                createProgressDialog("正在查询,请稍候...!");
                if (produceScheduleAdapter == null) {

                    produceSchedules = new ArrayList<ProducePro.DataEntity>();
                    mPresenter.queryProd(getRdsno(), getCustid(), getCode(),
                            getStartDate(), getEndDate(), getStype(), getMoreCom(), getUserId(), getJMark(), pageSize);
                } else {
                    Log.d(TAG, "onClick: else" + getStartDate());
                    throwable = null;
                    i = 0;
                    produceScheduleAdapter.deleteItems(produceSchedules);
                    produceSchedules.clear();
                    onRefresh();
                }
            }
        });
    }

    @Override
    protected void otherViewClick(View view) {
        ed_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectCalendar();
            }
        });
        ed_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectEndCalendar();
            }
        });
    }

    @Override
    protected ProduceSchedulePresenter loadPresenter() {
        return new ProduceSchedulePresenter();
    }

    @Override
    public void onRefresh() {
        if ((mRecyclerView.getChildCount() > 0) && (!getRdsno().isEmpty() || !getCustid().isEmpty() || !getCode().isEmpty() || getStartDate() != 0 || getEndDate() != 0)) {
            Log.d(TAG, "onRefresh: " + mRecyclerView.getChildCount());
            mRecyclerView.removeAllViews();
            produceSchedules.clear();
            produceScheduleAdapter = null;
            mFooterRecyclerViewAapter = null;
            Log.d(TAG, "onRefresh: " + getStartDate());
            mPresenter.queryProd(getRdsno(), getCustid(), getCode(), getStartDate(), getEndDate(), getStype(), getMoreCom(), getUserId(), getJMark(), 0);
            throwable = null;
            i = 0;
            mSwipeRefresh.setRefreshing(false);
        } else if ((mRecyclerView.getChildCount() <= 0) && (!getRdsno().isEmpty() || !getCustid().isEmpty() || !getCode().isEmpty() || getStartDate() != 0 || getEndDate() != 0)) {
            Log.d(TAG, "onRefresh: else if " + mRecyclerView.getChildCount());
            mRecyclerView.removeAllViews();
            produceScheduleAdapter = null;
            mFooterRecyclerViewAapter = null;
            produceSchedules.clear();
            mPresenter.queryProd(getRdsno(), getCustid(), getCode(), getStartDate(), getEndDate(), getStype(), getMoreCom(), getUserId(), getJMark(), 0);
            mSwipeRefresh.setRefreshing(false);
        }
    }

    @Override
    public String getRdsno() {
        return ed_2.getText().toString();
    }

    @Override
    public String getCustid() {
        return ed_1.getText().toString();
    }

    @Override
    public String getCode() {
        return ed_5.getText().toString();
    }

    @Override
    public long getStartDate() {
        if (!ed_4.getText().toString().isEmpty()) {
            startMilli = changeMilli(ed_4.getText().toString());
        }
        return startMilli;
    }

    @Override
    public long getEndDate() {
        if (!ed_3.getText().toString().isEmpty()) {
            endMilli = changeMilli(ed_3.getText().toString());
        }
        return endMilli;
    }

    @Override
    public String getStype() {
        String stype = mySetting.getString("rCode", "");
        Log.d(TAG, "getStype: " + stype);
        return stype;
    }

    @Override
    public String getMoreCom() {
        String moreCom = mySetting.getString("rMoreCom", "");
//        Log.d(TAG, "getMoreCom: "+moreCom);
        return moreCom;
    }

    @Override
    public int getUserId() {
        int userId = mySetting.getInt("mId", 0);
        return userId;
    }

    @Override
    public String getJMark() {
        boolean isSale = mySetting.getBoolean("isSale", false);
        int grpAuthority = mySetting.getInt("groupAuthority", 0);

        if (isSale && grpAuthority == 0) {
            return "1";
        } else if (!isSale && grpAuthority == 0) {
            return "0";
        } else {
            return "2";
        }

    }

    @Override
    public void queryPSSuccess(List<ProducePro.DataEntity> produce) {
        mProgressDialog.dismiss();
        for (ProducePro.DataEntity dev : produce) {
            produceSchedules.add(dev);
        }
        setProduceScheduleAdapter();
//        if (arrow_statue) {
//            touchEvent();
//        }
    }


    @Override
    public void queryPSFail(String failMsg) {
        mProgressDialog.dismiss();
        this.throwable = new Throwable();
        if (failMsg.substring(failMsg.indexOf(":") + 1).trim().equals("暂无合适的数据")) {

            RecyclerViewStateUtils.setFooterViewState(getActivity(),
                    mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
            ToastUtil.showToast(getActivity(), failMsg.substring(failMsg.indexOf(":") + 1).trim());
        } else {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), this.mRecyclerView, REQUEST_COUNT, LoadingFooter.State.NetWorkError, this.mFooterClick);
            ToastUtil.showToast(getActivity(), "网络连接有误");
        }
    }


    private void setProduceScheduleAdapter() {
        if (produceScheduleAdapter == null) {
            produceScheduleAdapter = new ProAdapter(getActivity());
            produceScheduleAdapter.addItems(produceSchedules);
            produceScheduleAdapter.addContext(getActivity());
            mFooterRecyclerViewAapter = new HeaderAndFooterRecyclerViewAdapter(produceScheduleAdapter);
            mRecyclerView.setAdapter(mFooterRecyclerViewAapter);
            RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView, LoadingFooter.State.Normal);
        } else {
            Log.d(TAG, "setNewAdapter: 2");
            mFooterRecyclerViewAapter.notifyDataSetChanged();
            produceScheduleAdapter.addItems(produceSchedules);
            RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView, LoadingFooter.State.Normal);
        }
    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tv_1.setText(detail[0]);
        tv_2.setText(detail[1]);
        tv_3.setText(detail[2]);
        tv_4.setText(detail[3]);
        tv_5.setText(detail[4]);
        initSRView(view);

        mRecyclerView.addOnScrollListener(mOnScrollListener);
    }

    public EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRecyclerView);
            Log.d(TAG, "onLoadNextPage: yx:" + (throwable != null) + ":" + (produceSchedules.size() % 10 == 0));
            if (state == LoadingFooter.State.Loading) {
                i++;
            }
            i++;
            if (throwable == null && (produceSchedules.size() % 10 == 0)) {


                produceSchedules = new ArrayList<ProducePro.DataEntity>();
                mPresenter.queryProd(getRdsno(), getCustid(), getCode(), getStartDate(), getEndDate(), getStype(), getMoreCom(), getUserId(), getJMark(), i);
                //    Log.d(TAG, "onLoadNextPage: "+getRdsno()+"："+getCustid()+":"+getCode()+"："+getStartDate()+"："+getEndDate()+"："+i);
                RecyclerViewStateUtils.
                        setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            } else if (throwable == null && (produceSchedules.size() % 10 != 0)) {
                //the end
                Log.d(TAG, "onLoadNextPage:  !-9 ");
                mPresenter.queryProd(getRdsno(), getCustid(), getCode(), getStartDate(), getEndDate(), getStype(), getMoreCom(), getUserId(), getJMark(), i);
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                throwable = null;
            } else if (throwable != null) {
                //the end
                i = 0;
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                throwable = null;
            }

        }
    };


    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            mPresenter.queryProd(getRdsno(), getCustid(), getCode(), getStartDate(), getEndDate(), getStype(), getMoreCom(), getUserId(), getJMark(), i);
        }
    };
}
